package business;

import utils.Convert;
import play.Logger;
import play.db.jpa.JPA;
import utils.JPAUtil;
import utils.NumberUtil;
import utils.PageBean;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

public class BaseBiz<T> {
    protected play.mvc.Scope.Params params = play.mvc.Scope.Params.current();
    protected int currPage = Constants.ONE;
    protected int pageSize = Constants.PAGE_SIZE;
    public PageBean<T> queryList(Class<T> type, StringBuilder sbSql, StringBuilder sbSqlCnt) {
        String currPageStr = params.get(Constants.KEY_CURR_PAGE); // 当前页
        String pageSizeStr = params.get(Constants.KEY_PAGE_SIZE); // 分页行数
        if (NumberUtil.isNumericInt(currPageStr)) {
            currPage = Integer.parseInt(currPageStr);
        }
        if (NumberUtil.isNumericInt(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        try {
            EntityManager em = JPA.em();
            Query query = em.createNativeQuery(sbSql.toString(), type);
            query.setFirstResult((currPage - 1) * pageSize);
            query.setMaxResults(pageSize);
            List<T> customerInfoList = query.getResultList();
            String countStr = JPAUtil.createNativeQuery(sbSqlCnt.toString()).getSingleResult().toString();
            int count = Convert.strToInt(countStr,0);
            PageBean<T> page = new PageBean();
            page.pageSize = pageSize;
            page.currPage = currPage;
            page.totalCount = count;
            page.page = customerInfoList;
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("BaseBiz.queryList.error:" + e.getMessage());
            return null;
        }
    }
}
